package com.fs.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.controller.BaseController;
import com.fs.mapper.*;
import com.fs.pojo.*;
import com.fs.service.OrderService;
import com.fs.vo.CommRequestVO;
import com.fs.vo.OrderVO;
import com.fs.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrderServiceImpl extends BaseController implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private UserAddrMapper userAddrMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsCartMapper goodsCartMapper;


    @Override
    public ResultVO list(CommRequestVO request) {
        if (request == null) return ResultVO.fail();

        int pageNum = request.getPageNum();
        int pageSize = request.getPageSize();

        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1) pageNum = 10;

        Page<Order> page = new Page(pageNum, pageSize);


        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.like(StrUtil.isNotBlank(request.getQuery()), "username", request.getQuery())
                .orderByDesc("id");
        page = orderMapper.selectPage(page, queryWrapper);
        request.setTotal(page.getTotal()).setRows(page.getRecords());

        return ResultVO.success(request);
    }

    @Transactional
    @Override
    public ResultVO buyGoods(OrderVO orderVO) {
        Integer totalNum = 0;
        Integer totalMoney = 0;
        Integer userId = getUserId();

        //检查是否有未付款的订单？如果有未付款的，则不能下单
//        QueryWrapper<Order> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("status", 0)
//                .eq("user_id", userId);
//        List<Order> ordersNoPay = orderMapper.selectList(queryWrapper);
//        if (ordersNoPay.size() > 0) {
//            return ResultVO.fail("您有订单还没有付款，请先完成付款");
//        }

        if (StrUtil.isBlank(orderVO.getMsg())) orderVO.setMsg(null);

        List<OrderGoods> goodsList = orderVO.getGoodsList();
        List<Integer> ids = new ArrayList();
        for (OrderGoods goods : goodsList) {
            ids.add(goods.getGoodsId());
            totalNum += goods.getNum();
            Goods entity = goodsMapper.selectById(goods.getGoodsId());
            totalMoney += entity.getPrice() * goods.getNum();
            goods.setPrice(entity.getPrice());
        }

        Date now = new Date();
        String orderNo = orderNo(now);
        Order orderEntity = new Order();
        orderEntity.setUserId(userId)
                .setOrderNo(orderNo)
                .setPrice(totalMoney)
                .setNum(totalNum)
                .setStatus(0)
                .setReceiving(0)
                .setAddrId(orderVO.getAddrId())
                .setMsg(orderVO.getMsg())
                .setCreated(now)
                .setUpdated(now);
        orderMapper.insert(orderEntity);

        for (OrderGoods g : goodsList) {
            g.setOrderId(orderEntity.getId());
            orderGoodsMapper.insert(g);
        }

        return ResultVO.success(orderEntity);
    }

    @Override
    public ResultVO getOrderByOrderId(String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_no", orderId);
        Order orderEntity = orderMapper.selectOne(queryWrapper);
        if (orderEntity == null) {
            return ResultVO.fail("订单有误");
        }
        if (orderEntity.getStatus().equals(1)) {
            return ResultVO.success("订单已支付", null);
        } else if (orderEntity.getStatus().equals(2)) {
            return ResultVO.success("订单已超时，请重新下单支付", null);
        }

        return ResultVO.success(orderEntity);
    }

    @Transactional
    @Override
    public ResultVO mockOrderByOrderId(String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_no", orderId)
                .eq("status", 0);
        Order orderEntity = orderMapper.selectOne(queryWrapper);
        if (orderEntity == null) {
            return ResultVO.fail("订单有误");
        }

        orderEntity.setStatus(1).setUpdated(new Date());
        orderMapper.updateById(orderEntity);
        return ResultVO.success();
    }

    @Override
    public ResultVO getOrderByOrderId2(String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_no", orderId);
        Order orderEntity = orderMapper.selectOne(queryWrapper);
        if (orderEntity == null) {
            return ResultVO.fail("订单有误");
        }

        return ResultVO.success(orderEntity);
    }

    @Override
    public ResultVO cartPay() {

        Integer totalNum = 0;
        Integer totalMoney = 0;
        Integer userId = getUserId();


        //检查是否有未付款的订单？如果有未付款的，则不能下单
//        QueryWrapper<Order> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("status", 0)
//                .eq("user_id", userId);
//        List<Order> ordersNoPay = orderMapper.selectList(queryWrapper);
//        if (ordersNoPay.size() > 0) {
//            return ResultVO.fail("您有订单还没有付款，请先完成付款");
//        }

        //留言  todo
//        if(StrUtil.isBlank(orderVO.getMsg()))orderVO.setMsg(null);

        Date now = new Date();

        //获取购物车未付款商品列表
        QueryWrapper<GoodsCart> wrapper = new QueryWrapper();
        wrapper.eq("status", false)
                .eq("user_id", getUserId());
        List<GoodsCart> goodsCartEntities = goodsCartMapper.selectList(wrapper);
        List<OrderGoods> goodsList = new ArrayList();
        List<Integer> ids = new ArrayList();
        for (GoodsCart g : goodsCartEntities) {
            totalMoney += g.getPrice() * g.getNum();
            totalNum += g.getNum();
            goodsList.add(new OrderGoods()
                    .setGoodsId(g.getGoodsId())
                    .setPrice(g.getPrice())
                    .setNum(g.getNum())
            );
            ids.add(g.getGoodsId());

            //将购物车状态改成true
            g.setStatus(true);
            goodsCartMapper.updateById(g);
        }

        //添加订单
        String orderNo = orderNo(now);
        Order orderEntity = new Order();
        orderEntity.setUserId(userId)
                .setOrderNo(orderNo)
                .setPrice(totalMoney)
                .setNum(totalNum)
                .setStatus(0)
                .setReceiving(0)
//                .setAddrId(orderVO.getAddrId())  todo
//                .setMsg(orderVO.getMsg())  todo
                .setCreated(now)
                .setUpdated(now);
        orderMapper.insert(orderEntity);

        //添加商品详情
        for (OrderGoods g : goodsList) {
            g.setOrderId(orderEntity.getId());
            orderGoodsMapper.insert(g);
        }


        return ResultVO.success(orderEntity);
    }

    @Override
    public ResultVO getOrderInfosByOrderId(String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_no", orderId);
        Order orderEntity = orderMapper.selectOne(queryWrapper);
        if (orderEntity == null) {
            return ResultVO.fail("订单有误");
        }
        List<Map<String, String>> orderGoods = orderGoodsMapper.getByOrderId(orderEntity.getId());
        Map<String, Object> map = new HashMap();
        map.put("order", orderEntity);
        map.put("goods", orderGoods);
        return ResultVO.success(map);
    }

    @Transactional
    @Override
    public ResultVO addAddr(Map<String, String> map) {
        String orderId = map.get("orderId");
        Integer addrId = Integer.valueOf(map.get("addrId"));
        String msg = map.get("msg");

        Integer userId = getUserId();


        //检查订单id是否存在
        QueryWrapper<Order> wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId)
                .eq("order_no", orderId)
                .eq("status", 0);
        Order orderEntity = orderMapper.selectOne(wrapper);
        if (orderEntity == null) {
            return ResultVO.fail("订单号有误");
        }
        //检查收货地址是否存在
        QueryWrapper<UserAddr> wrapper2 = new QueryWrapper();
        wrapper2.eq("id", addrId)
                .eq("user_id", userId);
        UserAddr addrEntity = userAddrMapper.selectOne(wrapper2);
        if (addrEntity == null) {
            return ResultVO.fail("地址有误");
        }

        orderEntity.setAddrId(addrId);
        if (StrUtil.isNotBlank(msg)) {
            orderEntity.setMsg(msg);
        }

        orderMapper.updateById(orderEntity);
        return ResultVO.success();
    }

    @Override
    public ResultVO getAll(CommRequestVO request) {


        if (request == null) return ResultVO.fail();

        int pageNum = request.getPageNum();
        int pageSize = request.getPageSize();

        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1) pageSize = 10;

        Page<Order> page = new Page(pageNum, pageSize);

        int offset = (pageNum - 1) * pageSize;
        Integer userId = getUserId();

        Map<String, Object> map = new HashMap();
        map.put("page", offset);
        map.put("userId", userId);
        map.put("size", pageSize);
        List<Order> list = new ArrayList();
        String type = request.getQuery();
        Long total = 0L;
        if ("all".equalsIgnoreCase(type)) {
            list = orderMapper.getAll(map);
            total = orderMapper.getAllTotal(map);
        } else if ("unPay".equalsIgnoreCase(type)) {
            list = orderMapper.getUnPay(map);
            total = orderMapper.getUnPayTotal(map);
        } else if ("havePay".equalsIgnoreCase(type)) {
            list = orderMapper.getHavePay(map);
            total = orderMapper.getHavePayTotal(map);
        } else if ("haveDliv".equalsIgnoreCase(type)) {
            list = orderMapper.getHaveDliv(map);
            total = orderMapper.getHaveDlivTotal(map);
        }

        request.setRows(list).setTotal(total);
        return ResultVO.success(request);
    }

    private String orderNo(Date now) {
        return DateUtil.format(now, "yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-", "").substring(10, 16);
    }


}
